﻿// ———————————————————————–
// <copyright file="IncidentLocationExtension.cs" company="The MITRE Corporation">
//    Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// IncidentLocationExtension.cs:
//
// A type containing the additional location fields necessary to adequately describe the location of an incident.
//
// Project: IC.NET - CAD Library
// Author:  Jim Cronin - MITRE
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.Xml;
using EDXLSharp.NIEMCore;
using EDXLSharp.NIEMMilOpsLib;

namespace EDXLSharp.NIEMCADLib
{
  /// <summary>
  /// A type containing the additional location fields necessary to adequately describe the location of an incident.
  /// </summary>
  public class IncidentLocationExtension : IComposable
  {
    public Address Address { get; set; }

    public AddressCrossStreet AddressCrossStreet { get; set; }

    public AddressGrid AddressGrid { get; set; }

    public MGRSCoordinate MGRSCoordinate { get; set; }

    public UTMCoordinate UTMCoordinate { get; set; }

    public IAreaRegion AreaRegion { get; set; }

    public bool? IsIntersection { get; set; }

    private static IDictionary<string, Func<XmlNode, IAreaRegion>> AreaRegionParsers = InitializeParseDictionary();

    private static IDictionary<string, Func<XmlNode, IAreaRegion>> InitializeParseDictionary()
    {
      IDictionary<string, Func<XmlNode, IAreaRegion>> dict = new Dictionary<string, Func<XmlNode, IAreaRegion>>();
      dict["LocationExternalPolygon"] = LocationExternalPolygon.Parse;
      dict["LocationEllipse"] = LocationEllipse.Parse;
      dict["LocationLineString"] = LocationLineString.Parse;
      return dict;
    }

    public static void RegisterAreaRegionParser(string elementName, Func<XmlNode, IAreaRegion> parseFunction)
    {
      if (string.IsNullOrEmpty(elementName))
      {
        throw new ArgumentNullException("elementName");
      }
      if (parseFunction == null)
      {
        throw new ArgumentNullException("parseFunction");
      }

      AreaRegionParsers[elementName] = parseFunction;
    }

    /// <summary>
    /// Initializes a new instance of IncidentLocationExtension
    /// </summary>
    public IncidentLocationExtension()
    {
    }

    /// <summary>
    /// Initializes a new instance of IncidentLocationExtension from an XML string
    /// </summary>
    /// <param name="xmlString">XML representation of a IncidentLocationExtension</param>
    /// <exception cref="System.ArgumentNullException">Thrown if xmlString is null</exception>
    /// <exception cref="System.ArgumentException">Thrown if xmlString is not valid XML, or is not a IncidentLocationExtension element</exception>
    public IncidentLocationExtension(string xmlString)
      : this()
    {
      if (string.IsNullOrWhiteSpace(xmlString))
      {
        throw new ArgumentException("XML must not be null or whitespace", "xmlString");
      }

      XmlDocument doc = new XmlDocument();
      try
      {
        doc.LoadXml(xmlString);
      }
      catch (XmlException xe)
      {
        throw new ArgumentException("Error parsing XML. See inner exception for details", xe);
      }

      this.ReadXML(doc.DocumentElement);
    }

    /// <summary>
    /// Writes this Object to an inline XML Document
    /// </summary>
    /// <param name="xwriter">Valid XMLWriter</param>
    /// <exception cref="System.ArgumentNullException">Thrown if xwriter is null</exception>
    public void WriteXML(XmlWriter xwriter)
    {
      if (xwriter == null)
      {
        throw new ArgumentNullException("xwriter");
      }

      xwriter.WriteStartElement(EDXLConstants.CADPrefix, "IncidentLocationExtension", EDXLConstants.CADNamespace);
      if (this.Address != null)
      {
        this.Address.WriteXML(xwriter);
      }
      if (this.AddressCrossStreet != null)
      {
        this.AddressCrossStreet.WriteXML(xwriter);
      }
      if(this.AddressGrid != null)
      {
        this.AddressGrid.WriteXML(xwriter);
      }
      if (this.MGRSCoordinate != null)
      {
        this.MGRSCoordinate.WriteXML(xwriter);
      }
      if(this.UTMCoordinate != null)
      {
        this.UTMCoordinate.WriteXML(xwriter);
      }
      if (this.AreaRegion != null)
      {
        this.AreaRegion.WriteXML(xwriter);
      }
      if (this.IsIntersection.HasValue)
      {
        xwriter.WriteElementString(EDXLConstants.CADPrefix, "AddressIntersectionIndicator", EDXLConstants.CADNamespace, this.IsIntersection.Value.ToString());
      }
      xwriter.WriteEndElement();
    }

    /// <summary>
    /// Reads this Object's values from an XML NodeList
    /// </summary>
    /// <param name="rootnode">Root XML Node of the Object Element</param>
    /// <exception cref="System.ArgumentNullException">Thrown if rootnode is null</exception>
    /// <exception cref="System.ArgumentException">Thrown if rootnode is not an IncidentLocationExtension</exception>
    public void ReadXML(XmlNode rootnode)
    {
      if (rootnode == null)
      {
        throw new ArgumentNullException("rootnode");
      }
      if (rootnode.LocalName != "IncidentLocationExtension")
      {
        throw new ArgumentException("rootnode is not a IncidentLocationExtension element");
      }
      
      foreach (XmlNode node in rootnode.ChildNodes)
      {
        switch (node.LocalName)
        {
          case "Address":
            this.Address = new Address();
            this.Address.ReadXML(node);
            break;
          case "AddressCrossStreet":
            this.AddressCrossStreet = new AddressCrossStreet();
            this.AddressCrossStreet.ReadXML(node);
            break;
          case "AddressGrid":
            this.AddressGrid = new AddressGrid();
            this.AddressGrid.ReadXML(node);
            break;
          case "MGRSCoordinate":
            this.MGRSCoordinate = new MGRSCoordinate();
            this.MGRSCoordinate.ReadXML(node);
            break;
          case "UTMCoordinate":
            this.UTMCoordinate = new UTMCoordinate();
            this.UTMCoordinate.ReadXML(node);
            break;
          case "AddressIntersectionIndicator":
            this.IsIntersection = bool.Parse(node.InnerText);
            break;
          default:
            if (AreaRegionParsers.ContainsKey(node.LocalName))
            {
              this.AreaRegion = AreaRegionParsers[node.LocalName](node);
              break;
            }
            throw new NotImplementedException("IncidentLocationExtension.ReadXML - unrecognized element not implemented");
        }
      }
    }

    /// <summary>
    /// Validates this IncidentLocationExtension
    /// </summary>
    public void Validate()
    {
      if(this.Address != null)
      {
        this.Address.Validate();
      }
      if(this.AddressCrossStreet != null)
      {
        this.AddressCrossStreet.Validate();
      }
      if(this.AddressGrid != null)
      {
        this.AddressGrid.Validate();
      }
      if (this.MGRSCoordinate != null)
      {
        this.MGRSCoordinate.Validate();
      }
      if (this.UTMCoordinate != null)
      {
        this.UTMCoordinate.Validate();
      }
      if (this.AreaRegion != null)
      {
        this.AreaRegion.Validate();
      }
    }
  }
}